<template>
  <div class="table-box">
    <ProTable ref="proTableRef" row-key="id" :columns :request-api="fetchList">
      <template #tableHeader>
        <div>
          <el-button type="primary" v-auth="'Area.Area.AddArea'" @click="open">新增</el-button>
        </div>
      </template>
    </ProTable>
    <Edit ref="editRef" @success="refresh"></Edit>
  </div>
</template>

<script lang="tsx" setup>
import { fetchAreaList, removeArea } from "@/api/modules/area";
import ProTable from "@/components/ProTable/index.vue";
import { ColumnProps, ProTableInstance } from "@/components/ProTable/interface";
import { ref } from "vue";
import Edit from "./components/edit.vue";
import { RefOpenEventProps } from "@/typings/interface";
import { AreaSchema } from "@/schema";
import { ElMessageBox, ElNotification } from "element-plus";
import { ResultEnum } from "@/enums/httpEnum";

const proTableRef = ref<ProTableInstance>();
const editRef = ref<RefOpenEventProps<AreaSchema>>();

function fetchList(params) {
  const { search } = params;
  const parent = { name: search?.parentName };
  delete search?.parentName;
  return fetchAreaList({
    ...params,
    ...{ search: { ...search, parent } }
  });
}

function open() {
  editRef.value?.open();
}

function refresh() {
  proTableRef.value?.getTableList();
}
function edit(row) {
  editRef.value?.open(row);
}

function remove(row) {
  ElMessageBox.confirm("提示", { type: "error", message: "是否删除当前数据？" })
    .then(() => {
      if (row?.id) {
        removeArea({ id: row.id }).then(r => {
          const { code, message } = r;
          if (code == ResultEnum.SUCCESS) {
            ElNotification.success("删除成功！");
            refresh();
          } else {
            ElNotification.error(message);
          }
        });
      }
    })
    .catch(err => {
      console.error(err);
    });
}

const columns: ColumnProps[] = [
  { type: "index", label: "序号", width: 80, fixed: "left" },
  { label: "区域名称", prop: "name", align: "left", headerAlign: "left", search: { el: "input" } },
  {
    label: "区域层级",
    prop: "level",
    enum: [
      { label: "1级", value: 1 },
      { label: "2级", value: 2 },
      { label: "3级", value: 3 },
      { label: "4级", value: 4 }
    ],
    search: {
      el: "select"
    }
  },
  { label: "区域编码", prop: "code", search: { el: "input" } },
  {
    label: "父级区域",
    prop: "parentName",
    search: { el: "input" },
    render: ({ row }) => {
      return <>{row.parent?.name ?? "--"}</>;
    }
  },
  {
    label: "操作",
    prop: "action",
    render: ({ row }) => {
      return (
        <>
          <el-button v-auth="Area.Area.EditArea" link type="primary" onClick={() => edit(row)}>
            编辑
          </el-button>
          <el-button v-auth="Area.Area.RemoveArea" link type="danger" onClick={() => remove(row)}>
            删除
          </el-button>
        </>
      );
    }
  }
];
</script>
